package com.tyk.bookstore.back.system.valid.validator;

import com.tyk.bookstore.back.common.core.valid.util.ValidUtil;
import com.tyk.bookstore.back.system.valid.annotation.UserFieldValid;
import com.tyk.bookstore.back.system.valid.constant.UserValidConstant;
import com.tyk.bookstore.back.system.valid.type.UserFieldValidType;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

import java.util.Arrays;

public class UserFieldConstraintValidator implements ConstraintValidator<UserFieldValid, Object> {
    private UserFieldValidType[] types;

    @Override
    public void initialize(UserFieldValid userFieldValid) {
        types = userFieldValid.value();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if(value == null) {
            return true;
        }

        for (UserFieldValidType type : types) {
            switch (type) {
                case ACCOUNT -> {
                    if(value instanceof String) {
                        return ValidUtil.validString((String) value ,UserValidConstant.ACCOUNT_MIN_LENGTH, UserValidConstant.ACCOUNT_MAX_LENGTH, UserValidConstant.ACCOUNT_PATTERN);
                    }
                }
                case PASSWORD -> {
                    if(value instanceof String) {
                        return ValidUtil.validString((String) value, UserValidConstant.PASSWORD_MIN_LENGTH, UserValidConstant.PASSWORD_MAX_LENGTH, UserValidConstant.PASSWORD_PATTERN);
                    }
                }
            }
        }

        throw new IllegalArgumentException("非法取值" + Arrays.toString(types) + value);
    }
}
